package com.apobates.forum.nanus.core;

import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
import java.util.Objects;

/**
 * 存储的载荷
 * @author xiaofanku@live.cn
 * @since 20210827
 */
public class NanusStoragePayload implements Serializable {
    //到期unix时间戳
    private final long stamp;
    //因子
    private final String factor;
    //值
    private final String hash;
    //内容格式
    private final String FORMAT_STYLE="hash:%s,factor:%s,stamp:%s";

    public NanusStoragePayload(long stamp, String factor, String hash) {
        this.stamp = stamp;
        this.factor = factor;
        this.hash = hash;
    }

    public long getStamp() {
        return stamp;
    }

    public String getFactor() {
        return factor;
    }

    public String getHash() {
        return hash;
    }

    @Override
    public String toString()throws IllegalArgumentException {
        if (StringUtils.isNotBlank(getHash()) && StringUtils.isNotBlank(getFactor())) {
            String data = String.format(FORMAT_STYLE, getHash(), getFactor(), getStamp()+"");
            return new NanusBASE64Strategy().encode(data, "");
        }
        throw new IllegalArgumentException("[Nanus]serialize field is Illegal");
    }

    /**
     * 使用指定的参数来还原存储载荷
     * @param value
     * @return
     * @throws IllegalStateException
     * @throws IllegalArgumentException
     */
    public static NanusStoragePayload getInstance(String value)throws IllegalStateException,IllegalArgumentException {
        Objects.requireNonNull(value);
        if (!StringUtils.isNotBlank(value)) {
            throw new IllegalArgumentException("[Nanus]serialize from argument is Illegal");
        }
        String decodeCV = new NanusBASE64Strategy().decode(value, null);
        if (null == decodeCV) {
            throw new IllegalArgumentException("[Nanus]serialize decode fail");
        }
        String[] data = decodeCV.split(",");
        if (data.length != 3) {
            throw new IllegalStateException("[Nanus]serialize from argument is lost part");
        }
        //hash:%s,factor:%s,stamp:%s
        //int stamp, String factor, String hash
        long currentStamp;
        try {
            currentStamp = Long.valueOf(data[2].replace("stamp:", "")).longValue();
        }catch (Exception e){
            currentStamp = System.currentTimeMillis() / 1000L;
        }
        return new NanusStoragePayload(
                currentStamp,
                data[1].replace("factor:", ""),
                data[0].replace("hash:", ""));
    }
}
